package com.hunk.core.web;

import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hunk.core.Constants;

/**
 * Description :<br>
 * 	Session Interceptor
 * 	对所有Controller请求进行拦截
 * @author HunkDeng
 * @since 2013-3-24
 */
public class SessionInterceptor extends HandlerInterceptorAdapter {
	
	private List<String> encludePath;
	private String errRelativePath;	
	
	public void setEncludePath(List<String> encludePath) {
		this.encludePath = encludePath;
	}
	public void setErrRelativePath(String errRelativePath) {
		this.errRelativePath = errRelativePath;
	}

	public boolean preHandle(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse, Object handler)
			throws Exception {
		// 查询是否是排除在外的请求
		String requestPath = httpServletRequest.getServletPath();
		for (String path : encludePath) {
			if (requestPath.startsWith(path))
				return super.preHandle(httpServletRequest, httpServletResponse, handler);
		}
		// 
		HttpSession map = httpServletRequest.getSession();
		if (null == map.getAttribute(Constants.LOGIN_USERNAME.name())) {
			httpServletRequest.setAttribute("message", "登陆超时，请重新登陆！");
			RequestDispatcher requestDispatcher = httpServletRequest
					.getRequestDispatcher(errRelativePath);
			requestDispatcher.forward(httpServletRequest, httpServletResponse);
			return false;
		}
		return super.preHandle(httpServletRequest, httpServletResponse, handler);
	}
}
